/**
 * 刷新
 * 
 * @Date 2012-09-17
 */
function refresh() {	
	if(window.parent.frames["main"]) {
		window.parent.frames["main"].location.reload();
	}
	window.location.reload();
}

/**
 * 全选
 * 
 * @Date 2012-09-17
 */
function selAll(name) {		
	var roomids = document.getElementsByName(name);   
	for (var j = 0; j < roomids.length; j++) {   
		if (roomids.item(j).checked == false) {   
			roomids.item(j).checked = true;   
		}   
	} 
}

/**
 * 取消
 * 
 * @Date 2012-09-17
 */
function cancel(name) {		
	var roomids = document.getElementsByName(name);   
	for (var j = 0; j < roomids.length; j++) {   
		if (roomids.item(j).checked == true) {   
			roomids.item(j).checked = false;   
		}   
	} 
}

/**
 * 反选
 * 
 * @Date 2012-09-17
 */
function Invert(name) {
	var s = document.getElementsByName(name);
	if(s){
		if(s.tagName){
			s.click();
		}else{
			for ( var i = 0; i < s.length; i++)
				s[i].click();
		}
	}	
}

/**
 * 删除已选
 * 
 * @Date 2012-09-17
 */
function delSelected(delUrl,name) {	
	var obj = document.getElementsByName(name);
	var count = 0;
	var rel ="";
	if(!obj) return false;
	if(!obj.length && obj.checked) return obj.value;
	for ( var i = 0; i < obj.length; i++) {
		if (obj[i].checked) {
			count++
			if(rel.length>0)rel+=",";
			rel += obj[i].value;
		}
	}
	if(count == 0){
		alert("请选择记录才能操作！");
		return false;
	}
	
	if(rel && window.confirm("删除无法恢复，你确定要删除吗？")){
		var url = delUrl;
		url +=  rel;
		$("#_form").attr("action", url);
		$("#_method").val("DELETE");
		$("#_form").submit();
	}	
}

/**
 * 删除未选
 * 
 * @Date 2012-09-17
 */
function delUnselected(delUrl,name) {	
	var obj = document.getElementsByName(name);	
	var rel ="";
	var count = 0;
	for ( var i = 0; i < obj.length; i++) {
		if (obj[i].checked == false) {
			count++
			if(rel.length>0)rel+=",";
			rel += obj[i].value;
		}
	}	
	if(rel && window.confirm("删除无法恢复，你确定要删除吗？")){
		var url = delUrl;
		url +=  rel;
		$("#_form").attr("action", url);
		$("#_method").val("DELETE");
		$("#_form").submit();
	}	
}

/**
 * 删除全部
 * 
 * @Date 2012-09-17
 */
function delAll(delUrl,name) {	
	var obj = document.getElementsByName(name);	
	var rel ="";
	var count = 0;
	for ( var i = 0; i < obj.length; i++) {		
		count++
		if(rel.length>0)rel+=",";
		rel += obj[i].value;	
	}	
	if(rel && window.confirm("删除无法恢复，你确定要删除吗？")){
		var url = delUrl;
		url +=  rel;
		$("#_form").attr("action", url);
		$("#_method").val("DELETE");
		$("#_form").submit();
	}	
}

/**
 * 扩展功能 判断结尾字符串
 * 
 * @author Administrator
 */
String.prototype.endWith = function(str) {
	if (str == null || str == "" || this.length == 0
			|| str.length > this.length)
		return false;
	if (this.substring(this.length - str.length) == str)
		return true;
	else
		return false;
	return true;
}

/**
 * 扩展功能 判断其实字符串
 * 
 * @author Administrator
 */
String.prototype.startWith = function(str) {
	if (str == null || str == "" || this.length == 0
			|| str.length > this.length)
		return false;
	if (this.substr(0, str.length) == str)
		return true;
	else
		return false;
	return true;
}

/**
 * 弹出模式对话框,默认宽600高500
 */
function showModal(url,width,height) {
	var rel;
	if(!width) width = 600;
	if(!height) height = 500;
	rel = showModalDialog(url, window,"dialogWidth:"+width+"px;dialogHeight:"+height+"px");
	return rel;
}

/**
 * 打开窗口,默认宽600高500
 * 
 * @param url
 * @param width
 * @param height
 * @return
 */
function showOpen(url,width,height) {
	var win ;
	if(!width) width = 600;
	if(!height) height = 500;
	var iTop = (window.screen.availHeight-30-height)/2;       // 获得窗口的垂直位置;
	var iLeft = (window.screen.availWidth-10-width)/2;           // 获得窗口的水平位置;
	win = window.open(url,'newwindow','height='+height+',,innerHeight='+height+',width='+width+',innerWidth='+width+',top='+iTop+',left='+iLeft+',toolbar=no,menubar=no,scrollbars=auto,resizeable=no,location=no,status=no');
	return win;
}


/**
 * 获取Select对象 selectInfo.count //选中总数 selectInfo.keys //选中值 selectInfo.status
 * //状态
 * 
 * @param obj
 * @return
 */
function getSelectInfo(obj) {
	var selectInfo = {
		count :0,
		keys :'',
		status :0
	};
	for ( var i = 0; i < obj.length; i++) {
		if (obj[i].checked) {
			selectInfo.count++;
			selectInfo.keys = obj[i].value;
			selectInfo.status = obj[i].status;
		}
	}
	return selectInfo;
}

/**
 * 只能单选
 * 
 * @param selectobj
 * @return
 */
function checkOneValue(selectobj) {
	var obj = document.getElementsByName(selectobj);
	var count = 0;
	var rel = false;
	if(!obj) return false;
	if(!obj.length && obj.checked) return obj.value;
	for ( var i = 0; i < obj.length; i++) {
		if (obj[i].checked) {
			count++
			rel = obj[i].value;
		}
	}
	if(count == 0){
		alert("请选择记录才能操作！");
	}else if(count > 1){
		alert("只能选择一条记录！");
		rel = false;
	}
	return rel;
}

/**
 * 可多选
 * 
 * @param selectobj
 * @return
 */
function checkManyValue(selectobj) {	
	var obj = document.getElementsByName(selectobj);
	var count = 0;
	var rel ="";
	if(!obj) return false;
	if(!obj.length && obj.checked) return obj.value;
	for ( var i = 0; i < obj.length; i++) {
		if (obj[i].checked) {
			count++
			if(rel.length>0)rel+=",";
			rel += obj[i].value;
		}
	}
	if(count == 0){
		alert("请选择记录才能操作！");
		return false;
	}
	return rel;
}

/**
 * 获取select为对象数组
 * 
 * @param selectobj
 * @return
 */
function getseltext(selectobj) {
	var obj = document.all(selectobj).options;
	for ( var i = 0; i < obj.length; i++) {
		if (obj[i].selected) {
			return obj[i].text;
		}
	}
}



/**
 * 列表的查询按钮
 * 
 * @return
 * @author 张彬
 * @Date 2012-03-26
 */
function dialogQuery() {	
	var obj = document.getElementById("query_bar");
	var rel = obj.style.display;
	var disHeight = 343 - $("#query_bar").height();
	if (rel == "none") {
		$(".dialog_div").css("height",disHeight);
		obj.style.display = "";
		queryForm.vQuery.value = "1";
	} else {
		$(".dialog_div").css("height",343);
		obj.style.display = "none";
		queryForm.vQuery.value = "0";
	}
}

/**
 * 列表式多选对话框的查询按钮
 * 
 * @return
 * @author 张彬
 * @Date 2012-03-26
 */
function multiQuery() {	
	var obj = document.getElementById("query_bar");
	var rel = obj.style.display;
	var disHeight = 343 - $("#query_bar").height();
	if (rel == "none") {
		$(".dialog_div").css("height",disHeight);
		$(".select_lump3").css("height",disHeight);
		$("#SelectList").css("height",disHeight);
		$(".arrow2").css("height",disHeight);
		obj.style.display = "";
	} else {
		$(".dialog_div").css("height",343);
		$(".select_lump3").css("height",343);
		$("#SelectList").css("height",343);
		$(".arrow2").css("height",343);
		obj.style.display = "none";
	}
}

function dataPageCheckChange(obj) 
{ 
	var row = obj.parentElement.parentElement;
	if(obj.checked){
		row.className = "selectRow";
	}else
		row.className = "";
} 

/**
 * 数据列表鼠标滑动效果
 */
function rowover(row) {
	if(row.className!="selectRow")
		row.className="overRow";
}

function rowout(row) {
	if(row.className!="selectRow")
		row.className="";
}

function rowclick(row) {
	var ckbox = window.event.srcElement.parentNode.firstChild.firstChild;
	if(ckbox){
		if (ckbox.type == "checkbox" || ckbox.type == "radio")  {
			ckbox.click();
		}
	}
}
/**
 * 反选
 * 
 * @param name
 * @return
 */
function selectReverse(name) {	
	var s = document.getElementsByName(name);
	if(s){
		if(s.tagName){
			s.click();
		}else{
			for ( var i = 0; i < s.length; i++)
				s[i].click();
		}
	}	
}

/**
 * 全部选择或取消
 * 
 * @param name
 * @return
 */
function selectAll(name) {
	// var rel = window.event.srcElement.checked;
	var rel = document.getElementsByName("checkAll")[0].checked;
	var s = document.getElementsByName(name);
	if(s){
		if(s.tagName){
			if(s.checked != rel) 
				s.click();
		}else{
			for ( var i = 0; i <= s.length; i++){
				if(s[i])
				if(s[i].checked != rel) 
					s[i].click();
			}
		}
	}
}

// ------------------------------------------------------------------------------------------
function moveUp(oSelect,isToTop)   // oSelect为数据源
 {
     // 默认状态不是移动到顶端
     if(isToTop == null)
         var isToTop = false;
         
     // 如果是多选------------------------------------------------------------------
     if(oSelect.multiple)
     {
         for(var selIndex=0; selIndex<oSelect.options.length; selIndex++)
         {
             // 如果设置了移动到顶端标志
             if(isToTop)
             {
                 if(oSelect.options[selIndex].selected)
                 {
                     var transferIndex = selIndex;
                     while(transferIndex > 0 && !oSelect.options[transferIndex - 1].selected)
                     {
                         oSelect.options[transferIndex].swapNode(oSelect.options[transferIndex - 1]);
                         transferIndex --;
                     }
                 }
             }
             // 没有设置移动到顶端标志
             else
             {
                 if(oSelect.options[selIndex].selected)
                 {
                     if(selIndex > 0)
                     {
                         if(!oSelect.options[selIndex - 1].selected)
                             oSelect.options[selIndex].swapNode(oSelect.options[selIndex - 1]);
                     }
                 }
             }
         }
     }
     // 如果是单选--------------------------------------------------------------------
     else
     {
         var selIndex = oSelect.selectedIndex;
         if(selIndex <= 0)
             return;
         // 如果设置了移动到顶端标志
         if(isToTop)
         {
             while(selIndex > 0)
             {
                 oSelect.options[selIndex].swapNode(oSelect.options[selIndex - 1]);
                 selIndex --;
             }
         }
         // 没有设置移动到顶端标志
         else        
             oSelect.options[selIndex].swapNode(oSelect.options[selIndex - 1]);
     }
 }
 
/**
 * 使选中的项目下移
 * 
 * oSelect: 源列表框 isToTop: 是否移至选择项到底端，其它依次上移， true为移动到底端，false反之，默认为false
 */
 function moveDown(oSelect,isToBottom)
 {
     // 默认状态不是移动到顶端
     if(isToBottom == null)
         var isToBottom = false;
         
     var selLength = oSelect.options.length - 1;
     
     // 如果是多选------------------------------------------------------------------
     if(oSelect.multiple)
     {
         for(var selIndex=oSelect.options.length - 1; selIndex>= 0; selIndex--)
         {
             // 如果设置了移动到顶端标志
             if(isToBottom)
             {
                 if(oSelect.options[selIndex].selected)
                 {
                     var transferIndex = selIndex;
                     while(transferIndex < selLength && !oSelect.options[transferIndex + 1].selected)
                     {
                         oSelect.options[transferIndex].swapNode(oSelect.options[transferIndex + 1]);
                         transferIndex ++;
                     }
                 }
             }
             // 没有设置移动到顶端标志
             else
             {
                 if(oSelect.options[selIndex].selected)
                 {
                     if(selIndex < selLength)
                     {
                         if(!oSelect.options[selIndex + 1].selected)
                             oSelect.options[selIndex].swapNode(oSelect.options[selIndex + 1]);
                     }
                 }
             }
         }
     }
     // 如果是单选--------------------------------------------------------------------
     else
     {
         var selIndex = oSelect.selectedIndex;
         if(selIndex >= selLength - 1)
             return;
         // 如果设置了移动到顶端标志
         if(isToBottom)
         {
             while(selIndex < selLength - 1)
             {
                 oSelect.options[selIndex].swapNode(oSelect.options[selIndex + 1]);
                 selIndex ++;
             }
         }
         // 没有设置移动到顶端标志
         else        
             oSelect.options[selIndex].swapNode(oSelect.options[selIndex + 1]);
     }
 }

function removeSelect(oSelect){
	oSelect.options[oSelect.selectedIndex] = null;
} 
 
function removeAll(oSelect){
	oSelect.options.length = 0;
}

function showAttach(divId){
	var div = document.getElementById(divId);
	if(div.style.display == "none"){
		div.style.display = "";
	}else{
		div.style.display = "none";
	}
}
 
function selected(checkbox)
{
	var TheName = checkbox.getAttribute("theText");
	var TheID = checkbox.value;
	var lis=document.getElementById("SelectedList");
    var IfAdd=true;     // 设置一个布尔变量来控制是否把当前人员姓名加入到已选人员列表中
    if (checkbox.checked){
	    for (var i=0;i<lis.options.length;i++){
		    if (lis.options[i].value==TheID){
			    IfAdd=false;				
			    break;
	        }
	    }
    }
    else{
        // document.all.checkall.checked=false;
		IfAdd=false;
		for (var i=0;i<lis.options.length;i++){
			if (lis.options[i].value==TheID){
				lis.options[i] = null;
				break;				
			}
		}
	}
	if(IfAdd){
	    lis.options.length=lis.options.length+1;
	    lis.options[lis.options.length-1].text = TheName;
	    lis.options[lis.options.length-1].value = TheID;
	}
 }
 
/**
 * url装换为JSON对象
 * 
 * @param str
 * @return
 */
function urlToJSON(str){
	  // 获取URL中的查询字符串参数
	  var argsArr = new Object();
	  // 这里的pairs是一个字符串数组
	  var pairs = str.split("&");// name=myname&password=1234&sex=male&address=nanjing
	  for(var i=0;i<pairs.length;i++){
	    var sign = pairs[i].indexOf("=");
	// 如果没有找到=号，那么就跳过，跳到下一个字符串（下一个循环）。
	    if(sign == -1){
	      continue;
	    }
	    var aKey = pairs[i].substring(0,sign);
	    var aValue = pairs[i].substring(sign+1);
	    if(argsArr[aKey])
	    	argsArr[aKey+i] = aValue;
	    argsArr[aKey] = aValue;
	  }
	  return argsArr;
}


/**
 * 格式化数字显示方式 用法 formatNumber(12345.999,'#,##0.00');
 * formatNumber(12345.999,'#,##0.##'); formatNumber(123,'000000');
 * 
 * @param num
 * @param pattern
 */
function formatNumber(num, pattern) {

	if(!pattern) pattern = "#,##0.00";
	var strarr = num ? num.toString().split('.') : [ '0' ];
	var fmtarr = pattern ? pattern.split('.') : [ '' ];
	var retstr = '';

	// 整数部分
	var str = strarr[0];
	var fmt = fmtarr[0];
	var i = str.length - 1;
	var comma = false;
	for ( var f = fmt.length - 1; f >= 0; f--) {
		switch (fmt.substr(f, 1)) {
		case '#':
			if (i >= 0)
				retstr = str.substr(i--, 1) + retstr;
			break;
		case '0':
			if (i >= 0)
				retstr = str.substr(i--, 1) + retstr;
			else
				retstr = '0' + retstr;
			break;
		case ',':
			comma = true;
			retstr = ',' + retstr;
			break;
		}
	}
	if (i >= 0) {
		if (comma) {
			var l = str.length;
			for (; i >= 0; i--) {
				retstr = str.substr(i, 1) + retstr;
				if (i > 0 && ((l - i) % 3) == 0)
					retstr = ',' + retstr;
			}
		} else
			retstr = str.substr(0, i + 1) + retstr;
	}

	retstr = retstr + '.';
	// 处理小数部分
	str = strarr.length > 1 ? strarr[1] : '';
	fmt = fmtarr.length > 1 ? fmtarr[1] : '';
	i = 0;
	for ( var f = 0; f < fmt.length; f++) {
		switch (fmt.substr(f, 1)) {
		case '#':
			if (i < str.length)
				retstr += str.substr(i++, 1);
			break;
		case '0':
			if (i < str.length)
				retstr += str.substr(i++, 1);
			else
				retstr += '0';
			break;
		}
	}
	return retstr.replace(/^,+/, '').replace(/\.$/, '');
}


/**
 * 设置输入框获得焦点改变样式
 */
$(document).ready( 
function(){
		if($.browser.msie){ 
			var f = $("body > form")
// var l = $("fieldset legend").focus(function()
// {$(this).css({background:"#FCFEAB"});})
// l.blur(function() {$(this).css({background:"#fff"});})
			
			// var i =
			// f.find("input[@type='text'][class!='form-date'],input[@type='password'],select,
			// textarea").focus(function()
			// {$(this).css({backgroundColor:"#FFFFD0"});})
			// i.blur(function() {$(this).css({backgroundColor:"#fff"});})
		}
	});

/**
 * 页面载入时，还原多选框选项
 * 
 * @param id
 *            保存id串的输入框id
 * @param name
 *            还原多选框选项的多选框name
 * @return
 * @author 张彬
 * @Date 2012-05-15
 */
function checkboxChecked(id,name){
	var checkValue = document.getElementById(id).value;
	var checkValues = checkValue.split(",");
	var checkbox = document.getElementsByName(name);
	if(checkValue != "" || checkValue != null){
		for(var i = 0;i < checkValues.length;i++){
			for(var j = 0;j < checkbox.length;j++){
				if(checkValues[i] == checkbox[j].value){
					checkbox[j].checked = "checked";
					break;
				}
			}
		}
	}
}

/**
 * 获得选中多选框的值，并拼接成字符串
 * 
 * @param id
 *            保存id串的输入框id
 * @param name
 *            还原多选框选项的多选框name
 * @return
 * @author 张彬
 * @Date 2012-05-15
 */
function getCheckedValue(id,name){
	var checkbox = document.getElementsByName(name);
	var checkValues = "";
	var count = 0;
	for(var i = 0;i < checkbox.length;i++){
		if(checkbox[i].checked){
			count++;
			if(count > 1){
				checkValues += "," + checkbox[i].value;
			}else{
				checkValues += checkbox[i].value;
			}
		}
	}
	document.getElementById(id).value = checkValues;
}

/**
 * 页面载入时，还原单选框选项
 * 
 * @param id
 *            保存值的隐藏域id
 * @param name
 *            还原单选框选项的单选框name
 * @return
 * @author 张彬
 * @Date 2012-05-15
 */
function radioChecked(id,name){
	var value = document.getElementById(id).value;
	var radio = document.getElementsByName(name);
	for(var i = 0;i < radio.length;i++){
		if(value == radio[i].value){
			radio[i].checked = "checked";
			break;
		}
	}
}

// JavaScript Document
// 浏览器判断
function browser()
{
	 var Sys = {};
      var ua = navigator.userAgent.toLowerCase();
      if (window.ActiveXObject)
          Sys.ie = ua.match(/msie ([\d.]+)/)[1]
      else if (document.getBoxObjectFor)
          Sys.firefox = ua.match(/firefox\/([\d.]+)/)[1]
      else if (window.MessageEvent && !document.getBoxObjectFor)
          Sys.chrome = ua.match(/chrome\/([\d.]+)/)[1]
      else if (window.opera)
          Sys.opera = ua.match(/opera.([\d.]+)/)[1]
      else if (window.openDatabase)
          Sys.safari = ua.match(/version\/([\d.]+)/)[1];
      
      // 以下进行测试
      if(Sys.ie) document.write('IE: '+Sys.ie);
      if(Sys.firefox) document.write('Firefox: '+Sys.firefox);
      if(Sys.chrome) document.write('Chrome: '+Sys.chrome);
      if(Sys.opera) document.write('Opera: '+Sys.opera);
      if(Sys.safari) document.write('Safari: '+Sys.safari);
}
// 分辨率控制
function RR()
{
	var Sys = {};
      var ua = navigator.userAgent.toLowerCase();
      if (window.ActiveXObject)
          Sys.ie = ua.match(/msie ([\d.]+)/)[1]
      else if (document.getBoxObjectFor)
          Sys.firefox = ua.match(/firefox\/([\d.]+)/)[1]
      else if (window.MessageEvent && !document.getBoxObjectFor)
          Sys.chrome = ua.match(/chrome\/([\d.]+)/)[1]
      else if (window.opera)
          Sys.opera = ua.match(/opera.([\d.]+)/)[1]
      else if (window.openDatabase)
          Sys.safari = ua.match(/version\/([\d.]+)/)[1];
      
  var RH = "";
	 if(Sys.chrome)
	 {
     RH = document.body.clientHeight+"px";
	 }
   else
   {
      RH = 443+(document.body.clientHeight-574)+"px";
    }
  var RA = document.getElementById("R_All");
  RA.style.height = RH;
}

// 主页时钟（时间判断相关）
function showLocale(objD)
{
	var str,colorhead,colorfoot;
	var yy = objD.getYear();
	if(yy<1900) yy = yy+1900;
	var MM = objD.getMonth()+1;
	if(MM<10) MM = '0' + MM;
	var dd = objD.getDate();
	if(dd<10) dd = '0' + dd;
	var hh = objD.getHours();
	if(hh<10) hh = '0' + hh;
	var mm = objD.getMinutes();
	if(mm<10) mm = '0' + mm;
	var ss = objD.getSeconds();
	if(ss<10) ss = '0' + ss;
	var ww = objD.getDay();
	if  ( ww==0 )  
	if  ( ww > 0 && ww < 6 )  
	if  ( ww==6 )
	if  (ww==0)  ww="星期日";
	if  (ww==1)  ww="星期一";
	if  (ww==2)  ww="星期二";
	if  (ww==3)  ww="星期三";
	if  (ww==4)  ww="星期四";
	if  (ww==5)  ww="星期五";
	if  (ww==6)  ww="星期六";
	str = yy + "年" + MM + "月" + dd + "日" + " " + hh + ":" + mm + ":" + ss + " " + ww;
	return(str);
 }
// 主页时钟（时间输出）
function tick()
{
var today;
today = new Date();
document.getElementById("mianTime").innerHTML = showLocale(today);
window.setTimeout("tick()", 1000);
}


// Iframe链接
function chageIframe(url){
 var urlValue = url;
 document.getElementById("desktopFrame").src = urlValue;
 resizeIFrame();
}

function chageWIframe(url){
 var urlValue = url;
 document.getElementById("WorkIframe").src = urlValue;
 document.getElementById("mian_Top").style.display = "none";
}


function SetWinHeight(obj)
{
 var win=obj;
 if (document.getElementById)
 {
   if (win && !window.opera)
   {
     if (win.contentDocument && win.contentDocument.body.offsetHeight) 

       win.height = win.contentDocument.body.offsetHeight; 
     else if(win.Document && win.Document.body.scrollHeight)
       win.height = win.Document.body.scrollHeight;
   }
 }
}


var Spry;
if (!Spry) Spry = {};
if (!Spry.Widget) Spry.Widget = {};
Spry.Widget.Accordion = function(element, opts)
{
	this.element = this.getElement(element);
	this.defaultPanel = 0;
	this.hoverClass = "AccordionPanelTabHover";
	this.openClass = "AccordionPanelOpen";
	this.closedClass = "AccordionPanelClosed";
	this.focusedClass = "AccordionFocused";
	this.enableAnimation = true;
	this.enableKeyboardNavigation = true;
	this.currentPanel = null;
	this.animator = null;
	this.hasFocus = null;

	this.previousPanelKeyCode = Spry.Widget.Accordion.KEY_UP;
	this.nextPanelKeyCode = Spry.Widget.Accordion.KEY_DOWN;

	this.useFixedPanelHeights = true;
	this.fixedPanelHeight = 0;

	Spry.Widget.Accordion.setOptions(this, opts, true);

	this.attachBehaviors();
};

Spry.Widget.Accordion.prototype.getElement = function(ele)
{
	if (ele && typeof ele == "string")
		return document.getElementById(ele);
	return ele;
};

Spry.Widget.Accordion.prototype.addClassName = function(ele, className)
{
	if (!ele || !className || (ele.className && ele.className.search(new RegExp("\\b" + className + "\\b")) != -1))
		return;
	ele.className += (ele.className ? " " : "") + className;
};

Spry.Widget.Accordion.prototype.removeClassName = function(ele, className)
{
	if (!ele || !className || (ele.className && ele.className.search(new RegExp("\\b" + className + "\\b")) == -1))
		return;
	ele.className = ele.className.replace(new RegExp("\\s*\\b" + className + "\\b", "g"), "");
};

Spry.Widget.Accordion.setOptions = function(obj, optionsObj, ignoreUndefinedProps)
{
	if (!optionsObj)
		return;
	for (var optionName in optionsObj)
	{
		if (ignoreUndefinedProps && optionsObj[optionName] == undefined)
			continue;
		obj[optionName] = optionsObj[optionName];
	}
};

Spry.Widget.Accordion.prototype.onPanelTabMouseOver = function(e, panel)
{
	if (panel)
		this.addClassName(this.getPanelTab(panel), this.hoverClass);
	return false;
};

Spry.Widget.Accordion.prototype.onPanelTabMouseOut = function(e, panel)
{
	if (panel)
		this.removeClassName(this.getPanelTab(panel), this.hoverClass);
	return false;
};

Spry.Widget.Accordion.prototype.openPanel = function(elementOrIndex)
{
	var panelA = this.currentPanel;
	var panelB;

	if (typeof elementOrIndex == "number")
		panelB = this.getPanels()[elementOrIndex];
	else
		panelB = this.getElement(elementOrIndex);
	
	if (!panelB || panelA == panelB)	
		return null;

	var contentA = panelA ? this.getPanelContent(panelA) : null;
	var contentB = this.getPanelContent(panelB);

	if (!contentB)
		return null;

	if (this.useFixedPanelHeights && !this.fixedPanelHeight)
		this.fixedPanelHeight = (contentA.offsetHeight) ? contentA.offsetHeight : contentA.scrollHeight;

	if (this.enableAnimation)
	{
		if (this.animator)
			this.animator.stop();
		this.animator = new Spry.Widget.Accordion.PanelAnimator(this, panelB, { duration: this.duration, fps: this.fps, transition: this.transition });
		this.animator.start();
	}
	else
	{
		if(contentA)
		{
			contentA.style.display = "none";
			contentA.style.height = "0px";			
		}
		contentB.style.display = "block";
		contentB.style.height = this.useFixedPanelHeights ? this.fixedPanelHeight + "px" : "auto";
	}

	if(panelA)
	{
		this.removeClassName(panelA, this.openClass);
		this.addClassName(panelA, this.closedClass);
	}

	this.removeClassName(panelB, this.closedClass);
	this.addClassName(panelB, this.openClass);

	this.currentPanel = panelB;

	return panelB;
};

Spry.Widget.Accordion.prototype.closePanel = function()
{
	// The accordion can only ever have one panel open at any
	// give time, so this method only closes the current panel.
	// If the accordion is in fixed panel heights mode, this
	// method does nothing.

	if (!this.useFixedPanelHeights && this.currentPanel)
	{
		var panel = this.currentPanel;
		var content = this.getPanelContent(panel);
		if (content)
		{
			if (this.enableAnimation)
			{
				if (this.animator)
					this.animator.stop();
				this.animator = new Spry.Widget.Accordion.PanelAnimator(this, null, { duration: this.duration, fps: this.fps, transition: this.transition });
				this.animator.start();
			}
			else
			{
				content.style.display = "none";
				content.style.height = "0px";
			}
		}		
		this.removeClassName(panel, this.openClass);
		this.addClassName(panel, this.closedClass);
		this.currentPanel = null;
	}
};

Spry.Widget.Accordion.prototype.openNextPanel = function()
{
	return this.openPanel(this.getCurrentPanelIndex() + 1);
};

Spry.Widget.Accordion.prototype.openPreviousPanel = function()
{
	return this.openPanel(this.getCurrentPanelIndex() - 1);
};

Spry.Widget.Accordion.prototype.openFirstPanel = function()
{
	return this.openPanel(0);
};

Spry.Widget.Accordion.prototype.openLastPanel = function()
{
	var panels = this.getPanels();
	return this.openPanel(panels[panels.length - 1]);
};

Spry.Widget.Accordion.prototype.onPanelTabClick = function(e, panel)
{
	if (panel != this.currentPanel)
		this.openPanel(panel);
	else
		this.closePanel();

	if (this.enableKeyboardNavigation)
		this.focus();

	if (e.preventDefault) e.preventDefault();
	else e.returnValue = false;
	if (e.stopPropagation) e.stopPropagation();
	else e.cancelBubble = true;

	return false;
};

Spry.Widget.Accordion.prototype.onFocus = function(e)
{
	this.hasFocus = true;
	this.addClassName(this.element, this.focusedClass);
	return false;
};

Spry.Widget.Accordion.prototype.onBlur = function(e)
{
	this.hasFocus = false;
	this.removeClassName(this.element, this.focusedClass);
	return false;
};

Spry.Widget.Accordion.KEY_UP = 38;
Spry.Widget.Accordion.KEY_DOWN = 40;

Spry.Widget.Accordion.prototype.onKeyDown = function(e)
{
	var key = e.keyCode;
	if (!this.hasFocus || (key != this.previousPanelKeyCode && key != this.nextPanelKeyCode))
		return true;
	
	var panels = this.getPanels();
	if (!panels || panels.length < 1)
		return false;
	var currentPanel = this.currentPanel ? this.currentPanel : panels[0];
	var nextPanel = (key == this.nextPanelKeyCode) ? currentPanel.nextSibling : currentPanel.previousSibling;

	while (nextPanel)
	{
		if (nextPanel.nodeType == 1 /* Node.ELEMENT_NODE */)
			break;
		nextPanel = (key == this.nextPanelKeyCode) ? nextPanel.nextSibling : nextPanel.previousSibling;
	}

	if (nextPanel && currentPanel != nextPanel)
		this.openPanel(nextPanel);

	if (e.preventDefault) e.preventDefault();
	else e.returnValue = false;
	if (e.stopPropagation) e.stopPropagation();
	else e.cancelBubble = true;

	return false;
};

Spry.Widget.Accordion.prototype.attachPanelHandlers = function(panel)
{
	if (!panel)
		return;

	var tab = this.getPanelTab(panel);

	if (tab)
	{
		var self = this;
		Spry.Widget.Accordion.addEventListener(tab, "click", function(e) { return self.onPanelTabClick(e, panel); }, false);
		Spry.Widget.Accordion.addEventListener(tab, "mouseover", function(e) { return self.onPanelTabMouseOver(e, panel); }, false);
		Spry.Widget.Accordion.addEventListener(tab, "mouseout", function(e) { return self.onPanelTabMouseOut(e, panel); }, false);
	}
};

Spry.Widget.Accordion.addEventListener = function(element, eventType, handler, capture)
{
	try
	{
		if (element.addEventListener)
			element.addEventListener(eventType, handler, capture);
		else if (element.attachEvent)
			element.attachEvent("on" + eventType, handler);
	}
	catch (e) {}
};

Spry.Widget.Accordion.prototype.initPanel = function(panel, isDefault)
{
	var content = this.getPanelContent(panel);
	if (isDefault)
	{
		this.currentPanel = panel;
		this.removeClassName(panel, this.closedClass);
		this.addClassName(panel, this.openClass);

		// Attempt to set up the height of the default panel. We don't want to
		// do any dynamic panel height calculations here because our accordion
		// or one of its parent containers may be display:none.

		if (content)
		{
			if (this.useFixedPanelHeights)
			{
				// We are in fixed panel height mode and the user passed in
				// a panel height for us to use.
	
				if (this.fixedPanelHeight)
					content.style.height = this.fixedPanelHeight + "px";
			}
			else
			{
				// We are in variable panel height mode, but since we can't
				// calculate the panel height here, we just set the height to
				// auto so that it expands to show all of its content.
	
				content.style.height = "auto";
			}
		}
	}
	else
	{
		this.removeClassName(panel, this.openClass);
		this.addClassName(panel, this.closedClass);

		if (content)
		{
			content.style.height = "0px";
			content.style.display = "none";
		}
	}
	
	this.attachPanelHandlers(panel);
};

Spry.Widget.Accordion.prototype.attachBehaviors = function()
{
	var panels = this.getPanels();
	for (var i = 0; i < panels.length; i++)
		this.initPanel(panels[i], i == this.defaultPanel);

	// Advanced keyboard navigation requires the tabindex attribute
	// on the top-level element.

	this.enableKeyboardNavigation = (this.enableKeyboardNavigation && this.element.attributes.getNamedItem("tabindex"));
	if (this.enableKeyboardNavigation)
	{
		var self = this;
		Spry.Widget.Accordion.addEventListener(this.element, "focus", function(e) { return self.onFocus(e); }, false);
		Spry.Widget.Accordion.addEventListener(this.element, "blur", function(e) { return self.onBlur(e); }, false);
		Spry.Widget.Accordion.addEventListener(this.element, "keydown", function(e) { return self.onKeyDown(e); }, false);
	}
};

Spry.Widget.Accordion.prototype.getPanels = function()
{
	return this.getElementChildren(this.element);
};

Spry.Widget.Accordion.prototype.getCurrentPanel = function()
{
	return this.currentPanel;
};

Spry.Widget.Accordion.prototype.getPanelIndex = function(panel)
{
	var panels = this.getPanels();
	for( var i = 0 ; i < panels.length; i++ )
	{
		if( panel == panels[i] )
			return i;
	}
	return -1;
};

Spry.Widget.Accordion.prototype.getCurrentPanelIndex = function()
{
	return this.getPanelIndex(this.currentPanel);
};

Spry.Widget.Accordion.prototype.getPanelTab = function(panel)
{
	if (!panel)
		return null;
	return this.getElementChildren(panel)[0];
};

Spry.Widget.Accordion.prototype.getPanelContent = function(panel)
{
	if (!panel)
		return null;
	return this.getElementChildren(panel)[1];
};

Spry.Widget.Accordion.prototype.getElementChildren = function(element)
{
	var children = [];
	var child = element.firstChild;
	while (child)
	{
		if (child.nodeType == 1 /* Node.ELEMENT_NODE */)
			children.push(child);
		child = child.nextSibling;
	}
	return children;
};

Spry.Widget.Accordion.prototype.focus = function()
{
	if (this.element && this.element.focus)
		this.element.focus();
};

Spry.Widget.Accordion.prototype.blur = function()
{
	if (this.element && this.element.blur)
		this.element.blur();
};

// ///////////////////////////////////////////////////

Spry.Widget.Accordion.PanelAnimator = function(accordion, panel, opts)
{
	this.timer = null;
	this.interval = 0;

	this.fps = 60;
	this.duration = 500;
	this.startTime = 0;

	this.transition = Spry.Widget.Accordion.PanelAnimator.defaultTransition;

	this.onComplete = null;

	this.panel = panel;
	this.panelToOpen = accordion.getElement(panel);
	this.panelData = [];
	this.useFixedPanelHeights = accordion.useFixedPanelHeights;

	Spry.Widget.Accordion.setOptions(this, opts, true);

	this.interval = Math.floor(1000 / this.fps);

	// Set up the array of panels we want to animate.

	var panels = accordion.getPanels();
	for (var i = 0; i < panels.length; i++)
	{
		var p = panels[i];
		var c = accordion.getPanelContent(p);
		if (c)
		{
			var h = c.offsetHeight;
			if (h == undefined)
				h = 0;

			if (p == panel && h == 0)
				c.style.display = "block";

			if (p == panel || h > 0)
			{
				var obj = new Object;
				obj.panel = p;
				obj.content = c;
				obj.fromHeight = h;
				obj.toHeight = (p == panel) ? (accordion.useFixedPanelHeights ? accordion.fixedPanelHeight : c.scrollHeight) : 0;
				obj.distance = obj.toHeight - obj.fromHeight;
				obj.overflow = c.style.overflow;
				this.panelData.push(obj);

				c.style.overflow = "hidden";
				c.style.height = h + "px";
			}
		}
	}
};

Spry.Widget.Accordion.PanelAnimator.defaultTransition = function(time, begin, finish, duration) { time /= duration; return begin + ((2 - time) * time * finish); };

Spry.Widget.Accordion.PanelAnimator.prototype.start = function()
{
	var self = this;
	this.startTime = (new Date).getTime();
	this.timer = setTimeout(function() { self.stepAnimation(); }, this.interval);
};

Spry.Widget.Accordion.PanelAnimator.prototype.stop = function()
{
	if (this.timer)
	{
		clearTimeout(this.timer);

		// If we're killing the timer, restore the overflow
		// properties on the panels we were animating!

		for (i = 0; i < this.panelData.length; i++)
		{
			obj = this.panelData[i];
			obj.content.style.overflow = obj.overflow;
		}
	}

	this.timer = null;
};

Spry.Widget.Accordion.PanelAnimator.prototype.stepAnimation = function()
{
	var curTime = (new Date).getTime();
	var elapsedTime = curTime - this.startTime;

	var i, obj;

	if (elapsedTime >= this.duration)
	{
		for (i = 0; i < this.panelData.length; i++)
		{
			obj = this.panelData[i];
			if (obj.panel != this.panel)
			{
				obj.content.style.display = "none";
				obj.content.style.height = "0px";
			}
			obj.content.style.overflow = obj.overflow;
			obj.content.style.height = (this.useFixedPanelHeights || obj.toHeight == 0) ? obj.toHeight + "px" : "auto";
		}
		if (this.onComplete)
			this.onComplete();
		return;
	}

	for (i = 0; i < this.panelData.length; i++)
	{
		obj = this.panelData[i];
		var ht = this.transition(elapsedTime, obj.fromHeight, obj.distance, this.duration);
		obj.content.style.height = ((ht < 0) ? 0 : ht) + "px";
	}
	
	var self = this;
	this.timer = setTimeout(function() { self.stepAnimation(); }, this.interval);
};
